package org.mclll.xwangplugin.town.command.executor;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.mclll.xwangplugin.town.database.domain.TownDO;
import org.mclll.xwangplugin.town.database.domain.TownPlayerDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownManage;
import org.mclll.xwangplugin.town.database.mapper.manage.TownPlayerManage;
import org.mclll.xwangplugin.town.enums.PlayerTownIdentity;
import org.mclll.xwangplugin.town.enums.TownLevel;
import org.mclll.xwangplugin.util.PlayerTools;

import java.time.LocalDateTime;

import static org.mclll.xwangplugin.town.config.TownContext.*;

public class TownSignExecutor {
    public static void sign(CommandSender sender, String[] args) {
        String SendCommand = "mm i give %s 心之石 %d";
        if (args.length != 3) {
            sender.sendMessage(TOWN_SIGN_COMMAND_FORMAT);
            return;
        }
        String playerName = args[2];
        OfflinePlayer playerOff = PlayerTools.getOfflineOrOnlinePlayerByName(playerName);
        if (!playerOff.isOnline()) {
            sender.sendMessage(String.format(PLAYER_OFFLINE, playerName));
            return;
        }
        Player player = (Player) playerOff;
        TownPlayerDO townPlayer = TownPlayerManage.selectByUuid(player.getUniqueId().toString());
        if (townPlayer.getIdentity() == PlayerTownIdentity.GENSHIN) {
            sender.sendMessage(String.format(PLAYER_NO_HAVE_TOWN, playerName));
            return;
        }
        TownDO town = TownManage.selectByUuid(townPlayer.getTownUuid());
        if (!args[1].equals(town.getName())) {
            sender.sendMessage(SIGN_ONLY_YOUR_TOWN);
            return;
        }
        // 背包满了无法领取心之石，签到失败
        if (playerInventoryIsFull(player.getInventory())) {
            player.sendMessage(BACKPACK_IS_FULL);
            return;
        }
        // 镇长领取暂存的心之石
        boolean receiveSaveHartStone = false;
        Double saveHartStone = town.getSaveHartStone();
        if (townPlayer.getIdentity() == PlayerTownIdentity.LEADER && saveHartStone >= 1) {
            receiveSaveHartStone = true;
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
                    String.format(SendCommand, player.getName(), saveHartStone.intValue()));
            player.sendMessage(String.format(SAVED_RECEIVE_SUCCESS, saveHartStone.intValue()));
            town.setSaveHartStone(saveHartStone - saveHartStone.intValue());
            TownManage.updateByUuid(town);
        }
        // 今天已经签到过了
        LocalDateTime signTime = townPlayer.getPlayerLastSubsidyTime();
        LocalDateTime now = LocalDateTime.now();
        if (signTime != null &&
        signTime.getDayOfMonth() == now.getDayOfMonth() &&
        signTime.getMonth() == now.getMonth()) {
            // 如果镇长领取心只石那么就不提示已经签到了
            if (!receiveSaveHartStone) {
                player.sendMessage(DUPLICATE_SIGN);
            }
            return;
        }
        // 更新玩家签到时间，发放心之石
        townPlayer.setPlayerLastSubsidyTime(now);
        TownPlayerManage.updateByUuid(townPlayer);
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
                String.format(SendCommand, player.getName(), town.getTownLevel().playerSalary()));
        player.sendMessage(SIGN_SUCCESS);
        double townLevelRewardCount = town.getTownLevel().leaderReturnGift();
        // 发放城镇心之石，用于镇长领取
        town.setSaveHartStone(saveHartStone + townLevelRewardCount);
        TownManage.updateByUuid(town);
        // 城镇复苏逻辑
        if (town.getTownLevel() == TownLevel.DUST) {
            boolean successTax = town.getMonthTax() >= TownLevel.I.totalTax();
            if (!successTax) {
                return;
            }
            boolean leaderSigned = TownPlayerManage.selectByUuid(town.getLeaderUuid()).getPlayerLastSubsidyTime().getDayOfYear() == now.getDayOfYear();
            if (!leaderSigned) {
                return;
            }
            TownPlayerDO selectParam = new TownPlayerDO();
            selectParam.setTownUuid(town.getUuid());
            int count = 0;
            for (TownPlayerDO tPlayer : TownPlayerManage.selectList(selectParam)) {
                if (tPlayer.getPlayerLastSubsidyTime().getDayOfYear() == now.getDayOfYear()) {
                    ++count;
                }
            }
            boolean fivePlayersSigned = count >= 5;
            if (!fivePlayersSigned) {
                return;
            }
            // 恢复到I级
            town.setTownLevel(TownLevel.I);
            town.setMonthTax(town.getMonthTax() - TownLevel.I.totalTax());
            town.setLastTaxTime(now);
            TownManage.updateByUuid(town);
        }
    }

    private static boolean playerInventoryIsFull(PlayerInventory playerInventory) {
        int count = 0;
        for (ItemStack content : playerInventory.getContents()) {
            if (content != null && content.getType() != Material.AIR) {
                ++count;
            }
        }
        // 减去，头盔，胸甲，裤头，靴子，副手
        ItemStack itemInOffHand = playerInventory.getItemInOffHand();
        if (itemInOffHand.getType() != Material.AIR) {
            --count;
        }
        for (ItemStack armorContent : playerInventory.getArmorContents()) {
            if (armorContent != null && armorContent.getType() != Material.AIR) {
                --count;
            }
        }
        // 减去，头盔，胸甲，裤头，靴子，副手
        return count == playerInventory.getSize() - 5;
    }
}
